package com.sen.common.utils;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;

/**
 * Properties Util函数.
 * 
 * @author sen
 */
public class PropertiesUtils {

	/** slf4j logger 日志记录器  */
	private static Logger LOG = LoggerFactory.getLogger(PropertiesUtils.class);
	
	/** 默认编码 */
	private static final String DEFAULT_ENCODING = "UTF-8";
	
	/** spring DefaultPropertiesPersister */
	private static PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
	
	/** spring DefaultResourceLoader */
	private static ResourceLoader resourceLoader = new DefaultResourceLoader();

	/**
	 * 载入一个或多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的载入.
	 * 文件路径使用Spring Resource格式, 文件编码使用UTF-8.
	 * 
	 * @param resourcesPaths 多个propertie的文件列表
	 * @return Properties
	 * @exception IOException
	 */
	public static Properties loadProperties(String... resourcesPaths) {
		Properties props = new Properties();

		for (String location : resourcesPaths) {

			if (LOG.isDebugEnabled()) LOG.debug("Loading properties file from:" + location);

			try {
				Resource resource = resourceLoader.getResource(location);
				EncodedResource encodedResource = new EncodedResource(resource, DEFAULT_ENCODING);
				propertiesPersister.load(props, encodedResource.getReader());
			} catch (IOException e) {
				LOG.error("Could not load properties from classpath:" + location + ": " + e.getMessage());
			} 
		}
		return props;
	}
}
